/*
 * @Author: liuying 247220246@qq.com
 * @Date: 2025-02-26 18:14:13
 * @LastEditors: liuying 247220246@qq.com
 * @LastEditTime: 2025-04-21 18:14:51
 * @FilePath: \my-book-react\src\pages\search\compoments\searchBar\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React from 'react';
// import { SearchBar, SearchBarRef } from '@taoyage/react-mobile-ui';
import { SearchBar, SearchBarRef } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { setUrlParams, removeUrlParams } from '@/utils/url';
import { setHistory } from '@/pages/search/utils';
import { useAppSelector, useAppDispatch } from '@/stores/hooks';
import { searchActions } from '@/pages/search/stores';

const BookSearchBar: React.FC = React.memo(() => {
  const dispatch = useAppDispatch();
  // 使用useNavigate进行页面跳转
  const navigate = useNavigate();
  // const [searchKeyword, setSearchKeyword] = React.useState<string>('');
  // 使用useAppSelector获取searchKeyword
  const searchKeyword = useAppSelector<string>((state) => state.search.searchKeyword);
  // 使用本地状态管理输入框值
  const [inputValue, setInputValue] = React.useState<string>(searchKeyword || '');
  // 创建一个ref，用于获取SearchBar组件的引用
  const searchRef = React.useRef<SearchBarRef>(null);

  // 定义onSearch函数，用于处理搜索事件
  const onSearch = (value: string) => {
    console.log(value);
    if (value === '' || !value) return;
    // 设置搜索历史
    setHistory(value);
    // 设置URL参数
    setUrlParams([['keyword', value]], '/search');
    dispatch(searchActions.setSearchKeyword(value));
    setInputValue(value); // 更新本地状态
  };
  // const setUrlParams = (value: string) => {
  //   if (!value) return;
  // };
  // 定义onCancel函数，用于处理取消搜索事件
  const onCancel = () => {
    navigate(-1);
    console.log('取消');
  };
  const onClear = () => {
    removeUrlParams(['keyword'], '/search');
    dispatch(searchActions.setSearchKeyword(''));
    dispatch(searchActions.setSearchMode(false));
    setInputValue(''); // 清空输入框值

    console.log('清空', '');
  };
  const onChange = (value: string) => {
    if (!value) {
      removeUrlParams(['keyword'], '/search');
      dispatch(searchActions.setSearchKeyword(''));
      dispatch(searchActions.setSearchMode(false));
    }
  };

  React.useEffect(() => {
    searchRef.current?.focus();
  }, []);
  React.useEffect(() => {
    if (searchKeyword) {
      dispatch(setSearchMode(true));
      // searchRef.current?.setValue(searchKeyword);
    }
  }, [dispatch, searchKeyword]);
  return (
    // <SearchBar showCancelButton />
    <SearchBar
      ref={searchRef}
      placeholder="请搜索书籍和作者"
      showCancelButton
      onSearch={onSearch}
      onCancel={onCancel}
      onClear={onClear}
      onChange={onChange}
    />
  );
});
export default BookSearchBar;
// export const BookSearchBarRef = React.forwardRef<SearchBarRef, any>((props, ref) => {
